package com.basic.ui.view.image

import com.bumptech.glide.load.Option
import com.bumptech.glide.load.Options
import com.bumptech.glide.load.model.*
import com.bumptech.glide.load.model.ModelLoader.LoadData
import java.io.InputStream

class HttpUrlLoader @JvmOverloads constructor(private val modelCache: ModelCache<GlideUrl, GlideUrl>? = null) :
    ModelLoader<GlideUrl, InputStream> {
    override fun buildLoadData(
        model: GlideUrl, width: Int, height: Int,
        options: Options
    ): LoadData<InputStream> {
        // GlideUrls memoize parsed URLs so caching them saves a few object instantiations and time
        // spent parsing urls.
        var url: GlideUrl? = model
        if (modelCache != null) {
            url = modelCache[model, 0, 0]
            if (url == null) {
                modelCache.put(model, 0, 0, model)
                url = model
            }
        }
        val timeout = options.get(TIMEOUT)!!
        return LoadData(url!!, HttpUrlFetcher(url, timeout))
    }

    override fun handles(model: GlideUrl): Boolean {
        return true
    }

    /**
     * The default factory for [HttpUrlLoader]s.
     */
    class Factory : ModelLoaderFactory<GlideUrl, InputStream> {
        private val modelCache = ModelCache<GlideUrl, GlideUrl>(500)
        override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<GlideUrl, InputStream> {
            return HttpUrlLoader(modelCache)
        }

        override fun teardown() {
            // Do nothing.
        }
    }

    companion object {
        /**
         * An integer option that is used to determine the maximum connect and read timeout durations (in
         * milliseconds) for network connections.
         *
         *
         * Defaults to 2500ms.
         */
        val TIMEOUT = Option.memory(
            "com.bumptech.glide.load.model.stream.HttpGlideUrlLoader.Timeout", 15000
        )
    }
}